<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="600px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { formSchema } from "./data"
  import { saveOrUpdateMpUser } from "./api"
  import { listMpTag } from "../mpTag/api"
  import { useMessage } from "/@/hooks/web/useMessage"

  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const accountId = ref("")
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 60,
    wrapperCol: {
      md: { span: 21 },
      sm: { span: 21 },
    },
    schemas: formSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    isUpdate.value = !!data?.isUpdate
    accountId.value = data.accountId
    const tags = await listMpTag({ accountId: accountId.value })

    setDrawerProps({ confirmLoading: false })
    if (unref(isUpdate)) {
      if (!data.record.tagIds) {
        data.record.tagIds = []
      }
      setFieldsValue({
        ...data.record,
      })
    }

    const option = tags.map((e) => {
      return {
        value: e.tagId,
        label: e.name,
      }
    })
    await updateSchema({
      field: "tagIds",
      componentProps: {
        optionFilterProp: "label",
        mode: "multiple",
        showSearch: true,
        options: unref(option),
      },
    })

    //禁用表单
    setProps({ disabled: !attrs.showFooter })
  })
  /**
   * 标题
   */
  const getTitle = computed(() => "编辑用户")
  /**
   * 提交
   */
  async function handleSubmit() {
    try {
      const values = await validate()
      setDrawerProps({ confirmLoading: true })
      //提交表单
      await saveOrUpdateMpUser({ ...values, accountId: unref(accountId), tagIds: values.tagIds.split(",") }, isUpdate.value)
      closeDrawer()
      emit("success")
      createMessage.success(`${getTitle.value}成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
